package com.cx.product.controller;


import com.cx.common.restful.BaseResult;
import com.cx.product.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cxy
 * @since 2022-02-14
 */
@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Resource
    private ProductMapper productMapper;

    private final String PRODUCT_KEY = "product_key:" ;

    final ExecutorService executor = Executors.newFixedThreadPool(50);

    int num = 100;

    @PostConstruct
    public void initProduct(){
        redisTemplate.opsForValue().set(PRODUCT_KEY+"1","90");
    }


    @GetMapping("/skillProduct/{id}")
    public BaseResult<?> skillProduct(@PathVariable("id") Long id){

        for (int i = 0; i < 1; i++) {
            executor.execute(()-> skill(id));
        }

        return BaseResult.error();
    }

    private BaseResult<?> skill(Long id) {
        final String key = PRODUCT_KEY + id;
        final String s = redisTemplate.opsForValue().get(key);
        final int number = Integer.parseInt(s);

        if(number<=0){
            System.out.println("已秒杀完");
            return BaseResult.error("已秒杀完");
        }

        redisTemplate.opsForValue().decrement(key);
        num = num - 1;
        System.out.println(Thread.currentThread().getName()+"线程抢到,还剩"+num);

//        final Product product = productMapper.selectById(id);
//        product.setNum(product.getNum()-1);
//        productMapper.updateById(product);
        return BaseResult.success();
    }


}

